package com.colin.base.background;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by Colin on 2020/3/14 15:01
 * email: colinzhaodong@gmail.com
 * desc: 计算不准确,通过标记位判断.发生错误行可以不用去了解
 *
 * @author zhaod
 */
public class MultiThreadsError implements Runnable{
	int index = 0;
	static MultiThreadsError instance = null;
	//CyclicBarrier 可以让线程同时等待 同时执行
	static volatile CyclicBarrier cyclicBarrier1 = new CyclicBarrier(2);
	static volatile CyclicBarrier cyclicBarrier2= new CyclicBarrier(2);
	static {
		instance = new MultiThreadsError();
	}
	static AtomicInteger realIndex = new AtomicInteger();
	static AtomicInteger wrongCount = new AtomicInteger();
	final boolean[] marked = new boolean[1000000];
	public static void main(String[] args) throws InterruptedException {
		Thread thread1 = new Thread(instance);
		Thread thread2 = new Thread(instance);
		thread1.start();
		thread2.start();
		thread1.join();
		thread2.join();
		System.out.println("表面结果"+instance.index);
		System.out.println("真正运行的次数"+realIndex);
		System.out.println("错误的次数"+wrongCount);
	}
	@Override
	public void run() {
		for (int i = 0; i < 10000; i++) {
			try {
				cyclicBarrier2.reset();
				cyclicBarrier1.await();
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (BrokenBarrierException e) {
				e.printStackTrace();
			}
			index++;
			try {
				cyclicBarrier1.reset();
				cyclicBarrier2.await();
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (BrokenBarrierException e) {
				e.printStackTrace();
			}
			realIndex.incrementAndGet();
			synchronized (instance) {
				if (marked[index]){
					System.out.println("发生了错误"+ index);
					wrongCount.incrementAndGet();
				}
				marked[index] = true;
			}
		}
	}

//	public synchronized void count(){
//		for (int i = 0; i < 10000; i++) {
//			index++;
//		}
//	}
}
